#include <windows.h>
#include <tchar.h>
#include "tracelog.h"
#include "dllmain.h"
#include "resource.h"
#include "log.h"
#include "ini.h"


HWND hwndDetail=NULL;
HWND hwndDetailEdit=NULL;
long pOldEDWndProc=0;

HWND getDetailHWND(){
	return hwndDetail;
}

void detailDialogResize(HWND hwnd){
	RECT r;
	GetClientRect(hwnd,&r);
	SetWindowPos( hwndDetailEdit,NULL,0,0,r.right,r.bottom,SWP_NOZORDER );
}

BOOL CALLBACK detailDialogProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam){
	switch(msg){
		case WM_SYSCOMMAND:
			switch (wParam) {
				case SC_CLOSE:
					ShowWindow(hwnd,SW_HIDE);
					return 1;
			}
			break;
//		case WM_DESTROY:
//			log("DBG: detailDialogProc: WM_DESTROY\n");
//			break;
		case WM_CLOSE:
			log(_T("DBG: detailDialogProc: WM_CLOSE\n"));
			ini_savewinpos(_T("tracelog.w_detail"),hwnd);
			DestroyWindow(hwnd);
			hwndDetail=NULL;
			break;
		case WM_KEYDOWN:
			if(wParam==VK_ESCAPE)ShowWindow(hwnd,SW_HIDE);
			break;
		case WM_SIZE:
			detailDialogResize(hwnd);
			break;
		case WM_INITDIALOG:
			hwndDetailEdit=GetDlgItem(hwnd,IDC_EDIT1);
			detailDialogResize(hwnd);
			ini_loadwinpos(_T("tracelog.w_detail"),hwnd);
			return 1;
	}
	return 0;
}

long CALLBACK editWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
	switch (message) {
		case WM_KEYDOWN:
			if(wParam==VK_ESCAPE)ShowWindow(hwndDetail,SW_HIDE);
			break;
	}
	return CallWindowProc( (WNDPROC)pOldEDWndProc, hWnd, message, wParam, lParam); 
}

BOOL createDetailWindow(HWND parent){
	hwndDetail=CreateDialog(getInstance(),MAKEINTRESOURCE(DLG_DETAIL),parent,detailDialogProc);
	if(!hwndDetail)return log_error(_T("createDetailWindow"));
	if ( !(pOldEDWndProc = GetWindowLong(hwndDetailEdit, GWL_WNDPROC)) ) {
		log_error(_T("createDetailWindow:GetWindowLong"));
		return NULL; 
	}
	
	if ( !SetWindowLong(hwndDetailEdit, GWL_WNDPROC, (long)editWndProc) ) {
		log_error(_T("createDetailWindow:SetWindowLong"));
		return NULL; 
	}
	return true;
}

BOOL showDetailWindow(){
	ShowWindow(hwndDetail,SW_SHOW);
	SetActiveWindow(hwndDetail);
	return 1;
}

BOOL resetDetailText(){
	SendMessage(hwndDetailEdit,WM_SETTEXT,0,0);
	return 1;
}

BOOL appendDetailText(_TCHAR*c){
	SendMessage(hwndDetailEdit,EM_REPLACESEL,0,(LPARAM)c);
	return 1;
}



